import axios from 'axios'
import { EventSourcePolyfill } from 'event-source-polyfill'
import { SendMessageParams, StreamEvent ,Conversation, Message} from '@/types/dify'
const api = axios.create({
  baseURL:process.env.VUE_APP_DIFY_API_URL || 'https://api.dify.cn',
  headers: {
    'Authorization': `Bearer ${process.env.VUE_APP_DIFY_API_KEY}`,
    'Content-Type': 'application/json'
  }
})

// 文件上传
export const uploadFile = async (file: File, userId: string): Promise<string> => {
  const formData = new FormData()
  formData.append('file', file)
  formData.append('user', userId)

  const { data } = await api.post<{ id: string }>('/files/upload', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
  return data.id
}

// 流式对话接口
export const streamChat = (
  params: SendMessageParams,
  userId: string,
  handlers: {
    onMessage: (event: StreamEvent) => void
    onError: (error: Error) => void
    onEnd: () => void
  }
): EventSource => {
  const body = {
    ...params,
    user: userId,
    response_mode: 'streaming'
  }

  const es = new EventSourcePolyfill('/chat-messages', {
    headers: {
      'Authorization': `Bearer ${process.env.VUE_APP_DIFY_API_KEY}`,
      'Content-Type': 'application/json'
    },
    method: 'POST',
    body: JSON.stringify(body)
  })

  es.onmessage = (event) => {
    try {
      const data: StreamEvent = JSON.parse(event.data)
      handlers.onMessage(data)
    } catch (error) {
      handlers.onError(new Error('Failed to parse event data'))
    }
  }

  es.onerror = (error) => {
    handlers.onError(new Error(`EventSource failed: ${error}`))
    es.close()
    handlers.onEnd()
  }

  return es
}

// 获取会话列表
export const fetchConversations = async (userId: string): Promise<Conversation[]> => {
  const { data } = await api.get<{ data: Conversation[] }>('/conversations', {
    params: { user: userId }
  })
  return data.data
}

// 获取消息历史
export const fetchMessages = async (
  conversationId: string,
  userId: string
): Promise<Message[]> => {
  const { data } = await api.get<{ data: Message[] }>('/messages', {
    params: {
      conversation_id: conversationId,
      user: userId
    }
  })
  return data.data
}

// 停止生成
export const stopGeneration = async (taskId: string, userId: string): Promise<void> => {
  await api.post(`/chat-messages/${taskId}/stop`, { user: userId })
}